var util = require('../../libs/util.js');
var app = getApp()
Page({
  data: {
    userInfo: {},
    is_verify:false,
    truename: app.globalData.truename,
    plate: app.globalData.plate||'',
    driver_id: app.globalData.driverId,
    vehicle_state:"",
    vehicle_id: app.globalData.vehicleId||'',
    CO_ID: app.globalData.CO_ID,
    vehicle_owner:"",
    totalService:{
      orderNumber:"0",
      mile:"0",
      duration:"0"
    },
    monthService: {
      orderNumber: "0",
      mile: "0",
      duration: "0"
    },
    incomeService:{
      total:0,
      business:0,
      attendance:0,
      ontime:0,
      grade:0,
      maintain:0,
      safety:0,
      lawabiding:0
    },
    work_status:true,
    driverLevel:'零星',
    vehicleLevel:'零星',
    tab:3
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },
  reLaunch:function(){
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
  gotoPage:function(e){
    // if (!this.data.is_verify) {
    //   this.setData({
    //     modalName: 'NoROLE'
    //   })
    //   return false;
    // }
    wx.navigateTo({
      url: e.currentTarget.dataset.url
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  perfectInformation: function () {
    wx.redirectTo({
      url: '/pages/auth/driverreg',
    })
  },
  registerVehicle: function () {
    wx.navigateTo({
      url: '/pages/auth/vehiclereg',
    })
  },
  onLoad: function (e) {
    wx.setNavigationBarTitle({ "title": app.appName +"--司机业务端" });
    var that = this;
    wx.showLoading({
      title: '请稍候...',
    });
    // if (app.globalData.is_verify == 1 && app.globalData.id_card != '') {
    //   this.setData({
    //     is_verify:true
    //   })
    // }
    //角色切换
    util.getRoleList(this, app.globalData.CO_ID, app.globalData.role_default, app.globalData.roleData);
    //更新数据
    that.setData({
      userInfo: app.globalData.userInfo,
      truename: app.globalData.truename,
      driver_id: app.globalData.driverId,
      vehicle_id: app.globalData.vehicleId,
      CO_ID: app.globalData.CO_ID,
      CO_NAME: app.globalData.CO_NAME,
      V_CO_ID: app.globalData.V_CO_ID || '',
      v_user_id: app.globalData.v_user_id || '',
      user_id: app.globalData.user_id
    });
    util.getData("/atapi/user/user/getDriverData", { openid: app.globalData.openid }, function (res) {
      console.log(res.data.data)
      if (res.data.success) {
        var driver_data = res.data.data[0][0], //司机基本信息
          totalData = res.data.data[1][0], //司机累计接单、里程和时长
          monthData = res.data.data[2][0],//司机本月接单、里程和时长
          lastMonthData = res.data.data[3][0],//司机上月接单、里程和时长
          attendanceData = res.data.data[4][0],//司机考勤
          myVehicleData = res.data.data[5][0]//个人车辆
        that.setData({
          driver_data:driver_data,
          plate: driver_data.plate||'',
          driver_id: driver_data.ID,
          vehicle_id: driver_data.V_ID,
          changeCompany:driver_data.changeCompany||'',
          work_status: (driver_data.is_work == "1" ? true : false),
          is_employee: driver_data.is_employee,
          totalService: {
            orderNumber: totalData.count,
            mile: Number(totalData.mile).toFixed(0),
            duration: Number(totalData.duration).toFixed(0)
          },
          monthService: {
            orderNumber: monthData.count,
            income: driver_data.is_employee == '0' ? monthData.franchiseDriverPrice : monthData.driverPrice,
            mile: Number(monthData.mile).toFixed(0),
            duration: Number(monthData.duration).toFixed(0),
            attendance: attendanceData.count
          },
          lastMonthService: {
            orderNumber: lastMonthData.count,
            income: driver_data.is_employee == '0' ? lastMonthData.franchiseDriverPrice : lastMonthData.driverPrice,
            mile: Number(lastMonthData.mile).toFixed(0),
            duration: Number(lastMonthData.duration).toFixed(0)
          },
          myVehicleData: myVehicleData||{}
        });
        
      }
      wx.hideLoading();
      setTimeout(function(){
        wx.hideLoading();
      },100)
    });
  },
  dispatchCompany:function(e){
    var that = this;
    var vehicleId = e.currentTarget.dataset.vehicleid;
    util.getData('/wechat/passport/getCompany', {}, function (res) {
      console.log(res.data.data)
      if (res.data.success) {
        that.setData({
          enterpriseList: res.data.data
        })
      }
    });
    that.setData({
      modalName : 'enterpriseModal'
    })
    
  },
  cancelDispatchCompany: function (e) {
    var that = this;
    var vehicleId = e.currentTarget.dataset.vehicleid;
    wx.showModal({
      title: '温馨提示',
      content: '确认要取消派遣吗？取消后，目前所在的承运商将无法给你派单',
      success(res) {
        if (res.confirm) {
          util.putData("/wechat/vehicle/cancelDispatchVehicleToCompany", {
            id: that.data.vehicle_id,
            CO_ID: app.globalData.CO_ID
          }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading();
            if (error) {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000
              });
              return false;
            }
            if (res.data.success) {
              wx.showModal({
                title: '温馨提示',
                content: '取消派遣成功！',
                success: function (res) {
                  wx.redirectTo({
                    url: '/pages/index/index'
                  })
                }
              })
            } else if (res.data.success == false) {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000,
                mask: true
              });
            }
          });
        }
      }
    })
    
  },
  addCompany:function(e){
    wx.navigateTo({
      url: '/pages/fleet/selectCompany'
    })
  },
  bindDriver: function (e) {
    var vehicleId = e.currentTarget.dataset.vehicleid;
    wx.navigateTo({
      url: '/pages/fleet/vehicleBindDriver?CO_ID=' + app.globalData.CO_ID + '&id=' + vehicleId
    })
  }, 
  deleteDriver: function (e) {
    var vehicleId = e.currentTarget.dataset.vehicleid;
    wx.showModal({
      title: '解除绑定',
      content: '是否确认解除本车辆所绑定的司机',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '请稍候...',
          });
          util.putData("vehicleUnBindDriver", {
            id: vehicleId,
            openid: app.globalData.openid,
            user_id: app.globalData.user_id,
            CO_ID: app.globalData.CO_ID
          }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading();
            if (error) {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000
              });
              return false;
            }
            if (res.data.success) {
              wx.showToast({
                title: "解除绑定成功",
                icon: 'success',
                success: function () {
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '/pages/driver/driverInfo'
                    })
                  }, 3000);
                }
              });
            } else {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000
              });
              return false;
            }
          });
        } else if (res.cancel) {
        }
      }
    })
  },
  bindMyVehicle: function (e) {
    var that = this;
    var myVehicleData = that.data.myVehicleData;
    if (myVehicleData.plate) {
      wx.showModal({
        title: '温馨提示',
        content: '是否绑回自有车辆【' + myVehicleData.plate + '】',
        success(res) {
          if (res.confirm) {
            if (myVehicleData.driver){
              wx.showModal({
                title: '温馨提示',
                content: '车辆已经绑定司机，是否强制绑回自己作为司机？',
                success(res) {
                  console.log(res)
                  if (res.confirm) {
                    console.log('vehicleMandatoryBindDriver')
                    that.bindOurVehicle();
                  }
                }
              })
            }else{
              that.bindOurVehicle();
            }
          }
        }
      })
    }
  }, 
  bindOurVehicle: function () {
    var that = this;
    var myVehicleData = that.data.myVehicleData;
    util.putData("vehicleMandatoryBindDriver", {
      vehicleId: myVehicleData.ID,
      driverId: that.data.driver_id,
      openid: app.globalData.openid,
      CO_ID: app.globalData.CO_ID
    }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
      }
      if (res.data.success) {
        wx.showToast({
          title: res.data.data,
          icon: 'success',
          success: function () {
            setTimeout(function () {
              wx.redirectTo({
                url: '/pages/driver/driverInfo'
              })
            }, 3000);
          }
        });
      } else {
        if (res.data.hasResult) {
          wx.showModal({
            title: '绑定失败',
            content: res.data.data,
            showCancel: false,
            success: function (res) {
            }
          })
          return false;
        } else {
          wx.showToast({
            title: res.data.data,
            image: '/images/wrong.png',
            duration: 3000
          });
          return false;
        }
      }
    });
  },
  enterpriseInput: function (e) {
    var that = this;
    var value = e.detail.value;
    var enterpriseList = that.data.enterpriseList;
    var _enterpriseList = [];
    for (var i = 0; i < enterpriseList.length; i++) {
      if (enterpriseList[i].CO_NAME.indexOf(value) > -1) {
        _enterpriseList.push(enterpriseList[i]);
      }
    };
    if (value == '') {
      _enterpriseList = [];
    }
    that.setData({
      _enterpriseList: _enterpriseList
    })
  },
  selectEnterprise: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var _enterpriseList = that.data._enterpriseList;
    for (var i = 0; i < _enterpriseList.length; i++) {
      if (_enterpriseList[i].CO_ID == id) {
        that.setData({
          CO_NAME: _enterpriseList[i].CO_NAME,
          CO_ID: _enterpriseList[i].CO_ID
        })
        util.putData("/wechat/vehicle/dispatchVehicleToCompany", {
          id: that.data.vehicle_id,
          company: _enterpriseList[i].CO_ID
        }, function (res, error) {
          console.log(res); console.log(error)
          wx.hideLoading();
          if (error) {
            wx.showToast({
              title: res.data.data,
              image: '/images/wrong.png',
              duration: 3000
            });
            return false;
          }
          if (res.data.success) {
            wx.showModal({
              title: '温馨提示',
              content: '派遣成功！',
              success: function (res) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            })
          } else if (res.data.success == false) {
            wx.showToast({
              title: res.data.data,
              image: '/images/wrong.png',
              duration: 3000,
              mask: true
            });
          }
        });
        that.hideModal();
        return false;
      }
    };
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  //角色切换
  changeRole: function (e) {
    var role = e.currentTarget.dataset.role;
    var co_id = e.currentTarget.dataset.co_id;
    app.globalData.role_default = role;
    app.globalData.CO_ID = co_id;
    util.putData("/atapi/user/user/changeDefaultRole", {
      role: role,
      user_id: app.globalData.user_id,
      CO_ID:co_id
    }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
      }
      if (res.data.success) {
        wx.showModal({
          title: '温馨提示',
          content: '切换默认角色成功！',
          showCancel:false,
          success: function (res) {
            
            wx.redirectTo({
              url: '/pages/index/index'
            })
          }
        })
      } else if (res.data.success == false) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.png',
          duration: 3000,
          mask: true
        });
      }
    });
  },
  //企业切换
  changeCompany: function (e) {
    util.getCompanyList(this, app.globalData.CO_ID, app.globalData.roleData);
    this.setData({
      modalName: 'companyListModal'
    })
  },
  //企业选择
  selectCompany: function (e) {
    var CO_ID = e.currentTarget.dataset.co_id;
    app.globalData.CO_ID = CO_ID;
    this.setData({
      modalName: null
    })
    util.getRoleList(this, app.globalData.CO_ID, '', app.globalData.roleData);
  },
  changeWorkStatus:function(){
    this.setData({
      work_status: !this.data.work_status
    })
  },
  changeVehicle:function(){
    wx.navigateTo({
      url: '/pages/driver/changeVehicle?driver=' + this.data.driver_id+'&vehicle='+this.data.vehicle_id
    })
  },
  openTrainingMiniapp:function(){
    wx.navigateToMiniProgram({
      appId: 'wx698acf81fa1cdd2d',
      path: '/pages/index/index',
      extraData: {
        mobile: app.globalData.mobile,
        name: app.globalData.truename
      },
      success(res) {
        
      }
    })
  },
  registerCompany: function () {
    util.registerCompany(app, this)
  },
  gotoScan: function () {
    util.driverScan();
  },
  gotoHome: function () {
    wx.redirectTo({
      url: '/pages/driver/orderList'
    })
  },
  gotoDriverInfo: function () {
    wx.redirectTo({
      url: '/pages/driver/driverInfo'
    })
  },
  gotoCurrentOrder: function () {
    wx.redirectTo({
      url: '/pages/driver/currentOrder'
    })
  },
  gotoIotBox: function () {
    wx.redirectTo({
      url: '/pages/driver/iotBox'
    })
  },
  gotoHistoryOrder: function () {
    wx.redirectTo({
      url: '/pages/driver/historyOrder'
    })
  },
  numberToChinese: function(number){
    var chnNumChar = {
      1: "一月",
      2: "二月",
      3: "三月",
      4: "四月",
      5: "五月",
      6: "六月",
      7: "七月",
      8: "八月",
      9: "九月",
      10: "十月",
      11: "十一月",
      12: "十二月"
    };
    return chnNumChar[Number(number)];
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'companyData',
      success(res) {
        var CO_ID = res.data.value, CO_NAME = res.data.CO_NAME;
        wx.removeStorageSync('companyData');
        wx.showModal({
          title: '温馨提示',
          content: '确定要申请加入公司：' + CO_NAME + '吗？',
          success(res) {
            if (res.confirm) {
              wx.showLoading({
                title: '请稍候...',
              });
              util.postData("/atapi/vehicle/vehicle/requestChangeCompany", { 
                vehicle: that.data.vehicle_id, 
                driver:that.data.driver_id,
                CO_ID: CO_ID,
                CO_NAME: CO_NAME,
                user_id:app.globalData.user_id,
                plate:that.data.plate||'',
                name:that.data.truename
              }, function (res, error) {
                console.log(res); 
                console.log(error)
                wx.hideLoading();
                if (error) {
                  wx.showModal({
                    title: '申请失败',
                    content: res.data.data,
                    success(res) {}
                  });
                  return false;
                }
                if (res.data.success) {
                  wx.showModal({
                    title: '申请成功',
                    content: '请等待'+ CO_NAME + '管理人员审核。',
                    success(res) {
                      if (res.confirm) {
                        wx.redirectTo({
                          url: '/pages/driver/driverInfo?tab=3'
                        })
                      }
                    }
                  });
                } else if (res.data.success == false) {
                  wx.showModal({
                    title: '申请失败',
                    content: res.data.data,
                    success(res) {}
                  });
                }
              });
            } else if (res.cancel) {
            }
          }
        })
      }
    })
  }
})
